config = require('./config')
fs = require('fs-extra')
glob = require('glob')
helper = require('./helper')
isWin = /^win/.test(process.platform)
path = require('path')
vueLoaderConfig = require('./vue-loader.conf')
vueWebTemp = helper.rootNode(config.templateDir)
webpack = require('webpack')
weexEntry = 'index': helper.root('entry.coffee')
hasPluginInstalled = fs.existsSync(helper.rootNode(config.pluginFilePath))

rules = [
    {
        test: /\.js$/
        use: [ { loader: 'babel-loader?cacheDirectory=true' } ]
        exclude: config.excludeModuleReg
    }
    {
        test: /\.coffee$/
        exclude: config.excludeModuleReg
        loader: [
            'babel-loader?cacheDirectory=true'
            'coffee-loader'
        ]
    }
]

getEntryFileContent = (source, routerpath) ->
    contents = undefined
    dependence = undefined
    entryContents = undefined
    relativePluginPath = undefined
    dependence = 'import Vue from \'vue\'\n'
    dependence += 'import weex from \'weex-vue-render\'\n'
    relativePluginPath = helper.rootNode(config.pluginFilePath)
    entryContents = fs.readFileSync(source).toString()
    contents = ''
    entryContents = dependence + entryContents
    entryContents = entryContents.replace(/\/\* weex initialized/, (match) ->
        'weex.init(Vue)\n' + match
    )
    if isWin
        relativePluginPath = relativePluginPath.replace(/\\/g, '\\\\')
    if hasPluginInstalled
        contents += '\n// If detact plugins/plugin.js is exist, import and the plugin.js\n'
        contents += 'import plugins from \'' + relativePluginPath + '\';\n'
        contents += 'plugins.forEach(function (plugin) {\n\u0009weex.install(plugin)\n});\n\n'
        entryContents = entryContents.replace(/\.\/router/, routerpath)
        entryContents = entryContents.replace(/weex\.init/, (match) ->
            '' + contents + match
        )
    entryContents

getRouterFileContent = (source) ->
    dependence = undefined
    routerContents = undefined
    dependence = 'import Vue from \'vue\'\n'
    routerContents = fs.readFileSync(source).toString()
    routerContents = dependence + routerContents
    routerContents

getEntryFile = ->
    entryFile = undefined
    routerFile = undefined
    entryFile = path.join(vueWebTemp, config.entryFilePath)
    routerFile = path.join(vueWebTemp, config.routerFilePath)
    fs.outputFileSync entryFile, getEntryFileContent(helper.root(config.entryFilePath), routerFile)
    fs.outputFileSync routerFile, getRouterFileContent(helper.root(config.routerFilePath))
    { index: entryFile }

# The entry file for web needs to add some library. such as vue, weex-vue-render
# 1. src/entry.js
# import Vue from 'vue';
# import weex from 'weex-vue-render';
# weex.init(Vue);
# 2. src/router/index.js
# import Vue from 'vue'
webEntry = getEntryFile()
plugins = [ new (webpack.BannerPlugin)(
    banner: '// { "framework": "Vue"} \n'
    raw: true
    exclude: 'Vue') ]
extensions = [
    '.js'
    '.vue'
    '.json'
    '.coffee'
]
# Config for compile jsbundle for web.
webConfig =
    entry: Object.assign(webEntry, 'vendor': [ path.resolve('node_modules/phantom-limb/index.js') ])
    output:
        path: helper.rootNode('./dist')
        filename: '[name].web.js'
    resolve:
        extensions: extensions
        alias: '@': helper.resolve('src')
    module: rules: [ {
        test: /\.vue(\?[^?]+)?$/
        use: [ {
            loader: 'vue-loader'
            options: Object.assign(vueLoaderConfig(
                useVue: true
                usePostCSS: false),
                optimizeSSR: false
                postcss: [
                    require('postcss-plugin-weex')()
                    require('autoprefixer')(browsers: [
                        '> 0.1%'
                        'ios >= 8'
                        'not ie < 12'
                    ])
                    require('postcss-plugin-px2rem')(
                        rootValue: 75
                        minPixelValue: 1.01)
                ]
                compilerModules: [ { postTransformNode: (el) ->
                    # to convert vnode for weex components.
                    require('weex-vue-precompiler')() el
                    return
} ])
        } ]
        exclude: config.excludeModuleReg
    } ].concat(rules)
    plugins: plugins

# Config for compile jsbundle for native.
weexConfig =
    entry: weexEntry
    output:
        path: path.join(__dirname, '../dist')
        filename: '[name].js'
    resolve:
        extensions: extensions
        alias: '@': helper.resolve('src')
    module: rules: [ {
        test: /\.vue(\?[^?]+)?$/
        use: [ {
            loader: 'weex-loader'
            options: vueLoaderConfig(useVue: false)
        } ]
        exclude: config.excludeModuleReg
    } ].concat(rules)
    plugins: plugins
    node: config.nodeConfiguration

module.exports = [
    webConfig
    weexConfig
]
